const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = 3002;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 确保上传目录存在
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 模拟数据存储
let data = {
  users: [
    {
      id: '1',
      nickname: '校园小助手',
      avatar: '/uploads/default-avatar.png',
      phone: '13800138000',
      createTime: new Date().toISOString()
    }
  ],
  news: [
    {
      id: '1',
      title: '校园新闻发布系统上线啦！',
      content: '欢迎使用校园新闻发布系统，这里可以发布和查看最新的校园资讯。',
      author: '校园小助手',
      coverImage: '',
      images: [],
      tags: ['系统', '公告'],
      viewCount: 100,
      likeCount: 20,
      commentCount: 5,
      createTime: new Date().toISOString()
    }
  ],
  board: [
    {
      id: '1',
      title: '欢迎来到表白墙',
      content: '这里是校园表白墙，可以匿名发布表白信息。',
      isAnonymous: false,
      images: [],
      viewCount: 50,
      likeCount: 10,
      commentCount: 3,
      userNickname: '校园小助手',
      userAvatar: '/uploads/default-avatar.png',
      createTime: new Date().toISOString()
    }
  ],
  jobs: [
    {
      id: '1',
      title: '校园兼职-图书馆助理',
      salary: '15元/小时',
      workTime: '周末 9:00-17:00',
      location: '图书馆',
      contactWay: '13800138001',
      content: '协助图书馆日常管理工作，整理书籍，维护秩序。',
      requirements: '责任心强，有耐心',
      images: [],
      viewCount: 80,
      commentCount: 2,
      userNickname: '图书馆管理员',
      userAvatar: '/uploads/default-avatar.png',
      createTime: new Date().toISOString()
    }
  ],
  lost: [
    {
      id: '1',
      type: 'lost',
      title: '丢失校园卡',
      content: '在食堂丢失校园卡，卡号：2021001234，如有拾到请联系我。',
      location: '第一食堂',
      contactWay: '13800138002',
      images: [],
      viewCount: 30,
      commentCount: 1,
      userNickname: '张同学',
      userAvatar: '/uploads/default-avatar.png',
      createTime: new Date().toISOString()
    }
  ],
  leave: [
    {
      id: '1',
      type: '病假',
      title: '感冒请假',
      startDate: '2024-01-15 08:00',
      endDate: '2024-01-16 18:00',
      reason: '感冒发烧，需要休息治疗',
      contactWay: '13800138003',
      attachments: [],
      status: 'pending',
      viewCount: 10,
      userNickname: '李同学',
      userAvatar: '/uploads/default-avatar.png',
      createTime: new Date().toISOString(),
      approvalRecords: []
    }
  ],
  comments: []
};

// API路由

// 用户相关
app.get('/api/user/info', (req, res) => {
  res.json({
    code: 200,
    message: 'success',
    data: data.users[0]
  });
});

// 文件上传
app.post('/api/upload/image', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({
      code: 400,
      message: '没有上传文件'
    });
  }
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      url: `/uploads/${req.file.filename}`
    }
  });
});

app.post('/api/upload/file', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({
      code: 400,
      message: '没有上传文件'
    });
  }
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      url: `/uploads/${req.file.filename}`,
      filename: req.file.originalname
    }
  });
});

// 新闻相关
app.get('/api/news/list', (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const start = (page - 1) * limit;
  const end = start + parseInt(limit);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: data.news.slice(start, end),
      total: data.news.length,
      page: parseInt(page),
      limit: parseInt(limit)
    }
  });
});

app.get('/api/news/detail/:id', (req, res) => {
  const news = data.news.find(item => item.id === req.params.id);
  if (!news) {
    return res.status(404).json({
      code: 404,
      message: '新闻不存在'
    });
  }
  
  // 增加浏览量
  news.viewCount++;
  
  res.json({
    code: 200,
    message: 'success',
    data: news
  });
});

app.post('/api/news/create', (req, res) => {
  const newNews = {
    id: uuidv4(),
    ...req.body,
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    createTime: new Date().toISOString()
  };
  
  data.news.unshift(newNews);
  
  res.json({
    code: 200,
    message: '发布成功',
    data: newNews
  });
});

// 表白墙相关
app.get('/api/board/list', (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const start = (page - 1) * limit;
  const end = start + parseInt(limit);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: data.board.slice(start, end),
      total: data.board.length,
      page: parseInt(page),
      limit: parseInt(limit)
    }
  });
});

app.get('/api/board/detail/:id', (req, res) => {
  const post = data.board.find(item => item.id === req.params.id);
  if (!post) {
    return res.status(404).json({
      code: 404,
      message: '帖子不存在'
    });
  }
  
  post.viewCount++;
  
  res.json({
    code: 200,
    message: 'success',
    data: post
  });
});

app.post('/api/board/create', (req, res) => {
  const newPost = {
    id: uuidv4(),
    ...req.body,
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    userNickname: req.body.isAnonymous ? '匿名用户' : '用户',
    userAvatar: '/uploads/default-avatar.png',
    createTime: new Date().toISOString()
  };
  
  data.board.unshift(newPost);
  
  res.json({
    code: 200,
    message: '发布成功',
    data: newPost
  });
});

// 兼职相关
app.get('/api/job/list', (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const start = (page - 1) * limit;
  const end = start + parseInt(limit);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: data.jobs.slice(start, end),
      total: data.jobs.length,
      page: parseInt(page),
      limit: parseInt(limit)
    }
  });
});

app.get('/api/job/detail/:id', (req, res) => {
  const job = data.jobs.find(item => item.id === req.params.id);
  if (!job) {
    return res.status(404).json({
      code: 404,
      message: '兼职信息不存在'
    });
  }
  
  job.viewCount++;
  
  res.json({
    code: 200,
    message: 'success',
    data: job
  });
});

app.post('/api/job/create', (req, res) => {
  const newJob = {
    id: uuidv4(),
    ...req.body,
    viewCount: 0,
    commentCount: 0,
    userNickname: '用户',
    userAvatar: '/uploads/default-avatar.png',
    createTime: new Date().toISOString()
  };
  
  data.jobs.unshift(newJob);
  
  res.json({
    code: 200,
    message: '发布成功',
    data: newJob
  });
});

// 失物招领相关
app.get('/api/lost/list', (req, res) => {
  const { page = 1, limit = 10, type } = req.query;
  let list = data.lost;
  
  if (type) {
    list = list.filter(item => item.type === type);
  }
  
  const start = (page - 1) * limit;
  const end = start + parseInt(limit);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: list.slice(start, end),
      total: list.length,
      page: parseInt(page),
      limit: parseInt(limit)
    }
  });
});

app.get('/api/lost/detail/:id', (req, res) => {
  const item = data.lost.find(item => item.id === req.params.id);
  if (!item) {
    return res.status(404).json({
      code: 404,
      message: '信息不存在'
    });
  }
  
  item.viewCount++;
  
  res.json({
    code: 200,
    message: 'success',
    data: item
  });
});

app.post('/api/lost/create', (req, res) => {
  const newItem = {
    id: uuidv4(),
    ...req.body,
    viewCount: 0,
    commentCount: 0,
    userNickname: '用户',
    userAvatar: '/uploads/default-avatar.png',
    createTime: new Date().toISOString()
  };
  
  data.lost.unshift(newItem);
  
  res.json({
    code: 200,
    message: '发布成功',
    data: newItem
  });
});

// 请假相关
app.get('/api/leave/list', (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const start = (page - 1) * limit;
  const end = start + parseInt(limit);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: data.leave.slice(start, end),
      total: data.leave.length,
      page: parseInt(page),
      limit: parseInt(limit)
    }
  });
});

app.get('/api/leave/detail/:id', (req, res) => {
  const leave = data.leave.find(item => item.id === req.params.id);
  if (!leave) {
    return res.status(404).json({
      code: 404,
      message: '请假申请不存在'
    });
  }
  
  leave.viewCount++;
  
  res.json({
    code: 200,
    message: 'success',
    data: leave
  });
});

app.post('/api/leave/create', (req, res) => {
  const newLeave = {
    id: uuidv4(),
    ...req.body,
    status: 'pending',
    viewCount: 0,
    userNickname: '用户',
    userAvatar: '/uploads/default-avatar.png',
    createTime: new Date().toISOString(),
    approvalRecords: []
  };
  
  data.leave.unshift(newLeave);
  
  res.json({
    code: 200,
    message: '申请提交成功',
    data: newLeave
  });
});

app.post('/api/leave/cancel/:id', (req, res) => {
  const leave = data.leave.find(item => item.id === req.params.id);
  if (!leave) {
    return res.status(404).json({
      code: 404,
      message: '请假申请不存在'
    });
  }
  
  leave.status = 'cancelled';
  
  res.json({
    code: 200,
    message: '撤销成功',
    data: leave
  });
});

// 评论相关
app.get('/api/comment/list/:postId', (req, res) => {
  const postComments = data.comments.filter(comment => comment.postId === req.params.postId);
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: postComments,
      total: postComments.length
    }
  });
});

app.post('/api/comment/create', (req, res) => {
  const newComment = {
    id: uuidv4(),
    ...req.body,
    userNickname: '用户',
    userAvatar: '/uploads/default-avatar.png',
    createTime: new Date().toISOString()
  };
  
  data.comments.push(newComment);
  
  res.json({
    code: 200,
    message: '评论成功',
    data: newComment
  });
});

// 搜索相关
app.get('/api/search', (req, res) => {
  const { keyword, type } = req.query;
  let results = [];
  
  if (!keyword) {
    return res.json({
      code: 200,
      message: 'success',
      data: {
        list: [],
        total: 0
      }
    });
  }
  
  const searchKeyword = keyword.toLowerCase();
  
  if (!type || type === 'news') {
    const newsResults = data.news.filter(item => 
      item.title.toLowerCase().includes(searchKeyword) || 
      item.content.toLowerCase().includes(searchKeyword)
    ).map(item => ({ ...item, type: 'news' }));
    results = results.concat(newsResults);
  }
  
  if (!type || type === 'board') {
    const boardResults = data.board.filter(item => 
      item.title.toLowerCase().includes(searchKeyword) || 
      item.content.toLowerCase().includes(searchKeyword)
    ).map(item => ({ ...item, type: 'board' }));
    results = results.concat(boardResults);
  }
  
  if (!type || type === 'job') {
    const jobResults = data.jobs.filter(item => 
      item.title.toLowerCase().includes(searchKeyword) || 
      item.content.toLowerCase().includes(searchKeyword)
    ).map(item => ({ ...item, type: 'job' }));
    results = results.concat(jobResults);
  }
  
  if (!type || type === 'lost') {
    const lostResults = data.lost.filter(item => 
      item.title.toLowerCase().includes(searchKeyword) || 
      item.content.toLowerCase().includes(searchKeyword)
    ).map(item => ({ ...item, type: 'lost' }));
    results = results.concat(lostResults);
  }
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      list: results,
      total: results.length
    }
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`校园生活圈API服务器运行在 http://localhost:${PORT}`);
  console.log('API文档:');
  console.log('- GET  /api/user/info - 获取用户信息');
  console.log('- POST /api/upload/image - 上传图片');
  console.log('- GET  /api/news/list - 获取新闻列表');
  console.log('- GET  /api/board/list - 获取表白墙列表');
  console.log('- GET  /api/job/list - 获取兼职列表');
  console.log('- GET  /api/lost/list - 获取失物招领列表');
  console.log('- GET  /api/leave/list - 获取请假列表');
  console.log('- GET  /api/search - 搜索功能');
});